﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;

namespace C
{
    public class ProductController
    {
        public static void Insert(Product a)
        {
            // Check category is left node
            if (!C.ProductCategoryController.IsLeafNode(a.CategoryID)) throw new Exception("Product category is not a leaf node");

            HCDataContext db = new HCDataContext();
            a.DateTimeInsert = DateTime.Now;
            a.LastEditDate = a.DateTimeInsert;
            a.OrderDisplay = 1;
            db.Products.InsertOnSubmit(a);
            db.SubmitChanges();
        }

        public static void Update(Product a, HCDataContext db)
        {
            // Check category is left node
            if (!C.ProductCategoryController.IsLeafNode(a.CategoryID)) throw new Exception("Product category is not a leaf node");

            a.LastEditDate = DateTime.Now;
            db.SubmitChanges();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            Product a = db.Products.Where(
                ik => ik.ProductID == id).First();

            // Check contraint
            if (a.Order_Products.Count > 0) throw new Exception("Khong the xoa vi van con Order_Products");

            // Xoa het images
            foreach (ProductImage image in a.ProductImages)
            {
                C.ProductImageController.Delete(image.ProductImageId);
            }

            // Xoa het Product_PropertyFilter
            db.Product_PropertyFilters.DeleteAllOnSubmit(a.Product_PropertyFilters);

            // Xoa het ProductPropertyValue
            db.ProductPropertyValues.DeleteAllOnSubmit(a.ProductPropertyValues);

            // Xoa product
            db.Products.DeleteOnSubmit(a);
            db.SubmitChanges();
        }

        public static Product GetByID(int id, HCDataContext db)
        {
            return db.Products.Where(
                ik => ik.ProductID == id).FirstOrDefault();
        }

        public static Product GetByID(int id)
        {
            return GetByID(id, new HCDataContext());
        }
    }
}